<template>
	<el-drawer
	  v-model="drawer.visible"
	  :title="drawer.title"
	  append-to-body
	  size="650"
	  @close="closeDialog"
	  :close-on-click-modal="false"
	>
		<div class="body">
			<div class="table-tool-bar" style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 8px;">
				<div>
					<el-button
					  v-hasPerm="['sys:user:add']"
					  type="primary"
					  icon="plus"
					  @click="handleOpenDialog()"
					>
					  新增
					</el-button>
					<el-button
					  v-hasPerm="'sys:user:delete'"
					  type="danger"
					  icon="delete"
					  :disabled="selectIds.length === 0"
					  @click="handleDelete()"
					>
					  删除
					</el-button>
				</div>
			</div>
			
			<div>
				<el-table v-loading="loading" border :data="pageData" height="calc(100vh - 260px)" @selection-change="handleSelectionChange">
				  <el-table-column type="selection" width="50" align="center" />
				  <el-table-column label="响应名称"  align="left" prop="name" />
				  <el-table-column label="响应标识"  align="left" prop="identifier" />
				  <el-table-column label="执行类型" width="200" align="left" >
					<template #default="scope">
					  <DictLabel v-model="scope.row.exec" code="sql_execute_type" />
					</template>
				  </el-table-column>
				  <el-table-column label="操作" fixed="right" width="150">
					<template #default="scope">
					  <el-button
						v-hasPerm="'biz:dbapi:api:edit'"
						type="primary"
						icon="edit"
						link
						size="small"
						@click="handleOpenDialog(scope.row)"
					  >
						编辑
					  </el-button>
					  
					  <el-button
						v-hasPerm="'biz:dbapi:api:delete'"
						type="danger"
						icon="delete"
						link
						size="small"
						@click="handleDelete(scope.row.id)"
					  >
						删除
					  </el-button>
					</template>
				  </el-table-column>
				</el-table>
			</div>
		</div>		
	
		<template #footer>
		  <div class="dialog-footer">
			<el-button @click="closeDialog" :loading="loading">取 消</el-button>
		  </div>
		</template>
		
		<el-dialog
		  v-model="dialog.visible"
		  :title="dialog.title"
		  width="500px"
		  :close-on-click-modal="false"
		  @close="handleCloseDialog"
		>
		  <el-form ref="reqArgumentsFormRef" :model="formData" :rules="rules" label-width="100px">
			<el-form-item label="所属类别" prop="categoryId">
			  <el-tree-select
			    v-model="formData.categoryId"
			    placeholder="请选择所属类别"
			    :data="categoryList"
			    filterable
			    check-strictly
			    :render-after-expand="false"
				:props="defaultProps"
				@change="handleCategoryChange"
			  />
			</el-form-item>
			
			<el-form-item label="SQL" prop="sqlId">
				<el-select v-model="formData.sqlId" placeholder="请选择结果集SQL" style="width: 100%">
				    <el-option
				      v-for="item in options"
				      :key="item.id"
				      :label="item.name"
				      :value="item.id"
				    />
				</el-select>
			</el-form-item>
			
			<el-form-item label="排序号" prop="sort">
			  <el-input-number v-model="formData.sort" :min="0" :max="9999" />
			</el-form-item>
			
		  </el-form>
		
		  <template #footer>
		    <div class="dialog-footer">
		      <el-button type="primary" @click="handleSubmit">确 定</el-button>
		      <el-button @click="handleCloseDialog">取 消</el-button>
		    </div>
		  </template>
		</el-dialog>
	</el-drawer>
</template>

<script lang="ts" setup>
	import { ref } from "vue";
	import { onMounted } from "vue";
	import DbapiAPI from "@/api/biz/dbapi";
	import DatasourceAPI from "@/api/biz/datasource";
	import { reactive } from "vue";
	import { ElForm } from "element-plus";
	import SqlAPI from '@/api/biz/sql';
	import {recurOptions} from "@/utils/TreeUtil";
	
	const loading = ref<boolean>(false);
	const dialog = ref({
		visible:false,
		title:'',
	});
	
	const drawer = ref({
		visible:false,
		title:'',
	});
	const apiData=ref<any>();
	const pageData = ref<any>();
	const selectIds = ref<string[]>([]);
	const dataSourceOptions = ref<any[]>();
	const reqArgumentsFormRef = ref(ElForm);
	const categoryList = ref<any[]>();
	const options = ref<any[]>();
	
	const defaultProps = {
	  children: 'children',
	  label: 'name',
	  value:'id'
	}
	
	const formData = reactive<any>({
	  sort: 1,
	});
	
	const rules = reactive({
	  sqlId: [{ required: true, message: "请选择执行SQL", trigger: "blur" }],
	  sort: [{ required: true, message: "请输入序号", trigger: "blur" }],
	});
	
	// 查询
	function handleQuery() {
	  loading.value = true;
	  DbapiAPI.getSqls({apiId:apiData.value?.id})
	    .then((data:any) => {
	      pageData.value = data;
	    })
	    .finally(() => {
	      loading.value = false;
	    });
	}
	
	// 重置查询
	function handleResetQuery() {
	  handleQuery();
	}
	
	function handleSelectionChange(selection: any[]) {
	  selectIds.value = selection.map((item) => item.id);
	}
	
	function handleDelete(id?: string) {
	  const ids = [id || selectIds.value].join(",");
	  if (!ids) {
	    ElMessage.warning("请勾选删除项");
	    return;
	  }
	
	  ElMessageBox.confirm("确认删除接口响应Sql?", "警告", {
	    confirmButtonText: "确定",
	    cancelButtonText: "取消",
	    type: "warning",
	  }).then(
	    function () {
	      loading.value = true;
	      DbapiAPI.deleteSqlByIds(ids)
	        .then(() => {
	          ElMessage.success("删除成功");
	          handleResetQuery();
	        })
	        .finally(() => (loading.value = false));
	    },
	    function () {
	      ElMessage.info("已取消删除");
	    }
	  );
	}
	
	const getCategoryList = async () => {
	  const res = await SqlAPI.getCategoryList({ keywords: '' });
	  categoryList.value = recurOptions(res,'');
	};
	
	
	const getOptions = async () => {
	  options.value = await SqlAPI.options({ categoryId: formData.categoryId });
	}
	
	const handleCategoryChange=()=>{
		getOptions();
	}
	
	async function openDialog(row?: any) {
		drawer.value.visible=true;
		drawer.value.title="接口【"+row.name+'】SQL配置';
		apiData.value=row;
		handleResetQuery();
	}
	
	const emits = defineEmits(['closeDialog'])
	const closeDialog=()=>{
		drawer.value.visible=false;
		drawer.value.title="";
		apiData.value="";
		apiData.value={};
		categoryList.value=[]
	}
	
	async function handleOpenDialog(row?: any) {
		dataSourceOptions.value = await DatasourceAPI.options({});
		dialog.value.visible = true;
		getCategoryList();
		if (row) {
			dialog.value.title = "修改响应Sql";
			Object.assign(formData, row);
			
			console.log(row);
			
			formData.categoryId=row.categoryId;
			getOptions();
		} else {
			dialog.value.title = "新增响应Sql";
		}
	}
	
	function handleSubmit() {
	  reqArgumentsFormRef.value.validate((valid: any) => {
	    if (valid) {
	      loading.value = true;
	      const roleId = formData.id;
	      if (roleId) {
	        DbapiAPI.saveSql({
				id:formData.id,
				sqlId:formData.sqlId,
				apiId:apiData.value?.id,
				sort:formData.sort
			})
	          .then(() => {
	            ElMessage.success("修改成功");
	            handleCloseDialog();
	            handleResetQuery();
	          })
	          .finally(() => (loading.value = false));
	      } else {
	        DbapiAPI.saveSql({
				id:formData.id,
				sqlId:formData.sqlId,
				apiId:apiData.value?.id,
				sort:formData.sort
			})
	          .then(() => {
	            ElMessage.success("新增成功");
	            handleCloseDialog();
	            handleResetQuery();
	          })
	          .finally(() => (loading.value = false));
	      }
	    }
	  });
	}
	
	// 关闭弹窗
	function handleCloseDialog() {
		dialog.value.visible = false;
		reqArgumentsFormRef.value.resetFields();
		reqArgumentsFormRef.value.clearValidate();
		formData.id="";
		formData.sqlId="";
		formData.sort=0;
	}
	
	defineExpose({
	  openDialog,closeDialog
	});
	
	onMounted(() => {
	});
</script>

<style scoped>
</style>